package com.vframework.system.org.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.util.StringUtil;
import com.util.UUIDUtil;
import com.vframework.base.controller.BaseController;
import com.vframework.base.exception.BaseException;
import com.vframework.base.model.BaseBean;
import com.vframework.common.constant.SessionConstant;
import com.vframework.common.service.DictService;
import com.vframework.system.menu.model.MenuBean;
import com.vframework.system.menu.service.MenuService;
import com.vframework.system.org.model.OrgBean;
import com.vframework.system.org.service.OrgService;
import com.vframework.system.role.service.RoleService;

/***************************************************************
 * Name:        OrgController.java
 * Create At:   2018年5月8日
 * Module:      
 * Description: [TODO功能描述] 机构管理
 * @author      ztshan
 * ------------------------------------------------------------
 * 修改历史
 * 序号         日期                       修改人               修改原因
 * 1    2018年5月8日      ztshan    
 * 2
***************************************************************/
@Controller
@RequestMapping("OrgController")
public class OrgController extends BaseController {

    private static final String BASE_PATH = "com/vframework/system/org/pages/";

    @Autowired
    private OrgService orgService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    
    /**
     * Author:shanzhitong Create At:2012-05-29 Description:
     * [系统管理-初始页面，查询组织信息列表]
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "begin")
    public String begin(Model model) throws Exception {
        return queryList(model);
    }
    
    /**
     * Author:shanzhitong Create At:2010-06-12 
     * Description: [系统运维-机构管理功能，查询机构列表]
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "queryList")
    public String queryList(Model model) throws Exception {
        try {
            String orgId = (String) request.getSession().getAttribute(SessionConstant.SESSION_ORG_ID);
            super.paramMap.put("param_orgId", orgId);
            //超级管理员可以查看所有
            String orgType = (String) request.getSession().getAttribute(SessionConstant.SESSION_ORG_TYPE);
            if ("0".equals(orgType)) {//业务机构----系统管理员
                super.paramMap.remove("param_orgId");
            }
            // 查询机构列表
            List<OrgBean> resultList = orgService.getOrgList(super.paramMap);
            model.addAttribute("resultList", resultList);
        } catch (BaseException e) {
            super.message("查询失败: " + e.getMessage());
            return BASE_PATH + "orgList";
        }
        return BASE_PATH + "orgList";
    }
    
    /**
     * Author:shanzhitong Create At:2010-06-12 
     * Description: [系统运维-用户管理功能，跳转到添加页面]
     * @return String
     */
    @RequestMapping(value = "add")
    public String add(Model model) {
        OrgBean orgBean = new OrgBean();
        orgBean.setOrgId(UUIDUtil.getRandomString(8).toUpperCase());
        model.addAttribute("orgBean", orgBean);
        model.addAttribute("method", "add");
        model.addAttribute("typeList", getOrgTypeListByJurisdiction());
        return BASE_PATH + "orgAdd";
    }

    /**
     * Author:shanzhitong Create At:2010-06-12 
     * Description: [系统运维-机构管理功能，修改机构-查询出机构的资料]
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "edit")
    public String edit(Model model) throws Exception {
        try {
            String orgId = request.getParameter("orgId");
            // 根据机构编号查询该机构信息
            OrgBean orgBean = orgService.getOrgById(orgId);
            List<OrgBean> porgList = new ArrayList<OrgBean>();
            if ("1".equals(orgBean.getLevel())) {
                OrgBean porgBean = new OrgBean();
                porgBean.setOrgId("0");
                porgBean.setOrgName("顶级机构");
                porgList.add(porgBean);
            } else {
                super.paramMap.put("param_level", Integer.parseInt(orgBean.getLevel()) - 1);
                String orgType = (String) request.getSession().getAttribute(SessionConstant.SESSION_ORG_TYPE);
                if (!"0".equals(orgType)) {
                    super.paramMap.put("param_orgId", orgBean.getPorgId());
                }
                porgList = orgService.getOrgList(super.paramMap);
            }
            OrgBean porgBean = new OrgBean();
            if (porgList != null && porgList.size() > 0) {
                porgBean = porgList.get(0);
            }
            model.addAttribute("orgBean", orgBean);
            model.addAttribute("method", "edit");
            model.addAttribute("porgBean", porgBean);
            model.addAttribute("typeList", getOrgTypeListByJurisdiction());
        } catch (BaseException e) {
            super.message("查询失败: " + e.getMessage());
            return BASE_PATH + "orgAdd";
        }
        return BASE_PATH + "orgAdd";
    }
    
    private List<BaseBean> getOrgTypeListByJurisdiction() {
        List<BaseBean> orgTypeList = DictService.getTypeList("org_type");
        String loginOrgType = (String)session.getAttribute(SessionConstant.SESSION_ORG_TYPE);
        //非系统企业不可查看全部
        if (!"0".equals(loginOrgType)) {
            Iterator<BaseBean> it = orgTypeList.iterator();
            while (it.hasNext()) {
                BaseBean baseBean = it.next();
                if ("0".equals(baseBean.getCode())) {
                    it.remove();
                    break;
                }
            }
        }
        return orgTypeList;
    }
    
    /**
     * Author:shanzhitong Create At:2012-10-25 
     * Description: [机构管理-添加功能，查询机构编号是否已存在]
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "checkOrgId")
    @ResponseBody
    private Integer checkOrgId(Model model) throws Exception {
        Integer count = orgService.getOrgIdExists((String)super.paramMap.get("orgId"));// 获取数据
        return count;
    }
    
    @RequestMapping(value = "getPorgList")
    @ResponseBody
    private Map<String, Object> getPorgList() throws Exception {
        String level = request.getParameter("level");
        String sessionLevel = (String) request.getSession().getAttribute(SessionConstant.SESSION_ORG_LEVEL);
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Integer lvl = 0;
        if (!StringUtil.isEmpty(level)) {
            lvl = Integer.parseInt(level) - 1;
            String orgType = (String) super.session.getAttribute(SessionConstant.SESSION_ORG_TYPE);
            if (!"0".equals(orgType) && Integer.parseInt(level) <= Integer.parseInt(sessionLevel)) {
                resultMap.put("code", "0001");
                resultMap.put("message", "不能设定高于当前企业级别的级别！");
                resultMap.put("result", sessionLevel);
                return resultMap;
            }
        } else {
            return null;
        } 
        if (lvl <= 0) {
            OrgBean orgBean = new OrgBean();
            orgBean.setOrgId("0");
            orgBean.setOrgName("顶级机构");
            List<OrgBean> result = new ArrayList<OrgBean>();
            result.add(orgBean);
            resultMap.put("code", "0000");
            resultMap.put("result", result);
            return resultMap;
        }
        super.paramMap.put("param_level", String.valueOf(lvl));
        String orgType = (String) request.getSession().getAttribute(SessionConstant.SESSION_ORG_TYPE);
        if (!"0".equals(orgType)) {
            super.paramMap.put("param_orgId", (String) request.getSession().getAttribute(SessionConstant.SESSION_ORG_ID));
        }
        List<OrgBean> porgList = orgService.getOrgList(super.paramMap);
        resultMap.put("code", "0000");
        resultMap.put("result", porgList);
        return resultMap;
    }
    
    /**
     * Author:shanzhitong Create At:2010-06-12 
     * Description: [系统运维-机构管理功能，保存新添加的机构]
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "addSave")
    public String addSave(OrgBean orgBean, Model model) throws Exception {
        try {
            orgService.insertOrg(orgBean);
            orgService.insertLog(super.MakeLogBean(super.LOG_ADD_KEY, "添加机构", orgBean.toString()));
            super.message("添加成功！");
        } catch (BaseException e) {
            super.message("添加失败: " + e.getMessage());
            return queryList(model);
        }
        return queryList(model);
    }

    /**
     * Author:shanzhitong Create At:2010-06-12 
     * Description: [系统运维-机构管理功能，保存修改]
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "editSave")
    public String editSave(OrgBean orgBean, Model model) throws Exception {
        try {
            orgService.updateOrg(orgBean);
            orgService.insertLog(super.MakeLogBean(super.LOG_UPDATE_KEY, "修改机构", orgBean.toString()));
            super.message("修改成功！");
        } catch (BaseException e) {
            super.message("修改失败: " + e.getMessage());
            return queryList(model);
        }
        return queryList(model);
    }

    /**
     * Author:shanzhitong Create At:2010-06-12 
     * Description: [系统运维-机构管理功能，批量删除机构信息]
     * @return String
     */
    @RequestMapping(value = "delete")
    public String delete(Model model) throws Exception {
        try {
            String[] ids = request.getParameterValues("ids");
            //验证orgIds下是否存在role
            super.paramMap.put("param_siIds", ids);
            int roleCount = roleService.getCount(super.paramMap);
            super.paramMap.remove("param_siIds");
            if (roleCount > 0) {
                super.message("删除失败：机构下存在角色，请先删除角色再删除机构");
                return queryList(model);
            }
            //验证是否存在下级机构
            super.paramMap.remove("param_siIds");
            super.paramMap.put("param_porgId", ids);
            int corgCount = orgService.getCount(super.paramMap);
            super.paramMap.remove("param_porgId");
            if (corgCount > 0) {
                super.message("删除失败：机构存在下级机构，请先删除下级机构再删除机构");
                return queryList(model);
            }
            // 删除机构信息
            orgService.deleteOrg(ids);
            super.message("删除成功！");
            orgService.insertLog(super.MakeLogBean(super.LOG_DELETE_KEY, "删除机构", super.paramMap.toString()));
        } catch (BaseException e) {
            super.message("删除失败: " + e.getMessage());
            return queryList(model);
        }
        return queryList(model);
    }
    
    /**
     * @return
     * 检验是否进行过菜单分配
     */
    @RequestMapping(value = "checkAuthOk")
    @ResponseBody
    public String checkAuthOk() {
        String ids = request.getParameter("orgId");
        String result = null;
        try {
            List<BaseBean> orgMenuList = orgService.getMenus(ids);
            if (orgMenuList == null || orgMenuList.size() == 0) {
                result = "0";//不存在
            } else {
                result = "1";//存在
            }
        } catch (BaseException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * Author:shanzhitong Create At:2017-09-01 Description:
     * [系统管理-机构管理，跳转到添加管理员页面]
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "adminAdd")
    public String adminAdd(Model model) throws BaseException {
        String id = request.getParameter("id");
        OrgBean orgBean = orgService.getOrgById(id);
        model.addAttribute("orgBean", orgBean);
        return BASE_PATH + "popup/" + "orgAdminAdd";
    }
    
    /**
     * Author:shanzhitong Create At:2017-09-01 
     * Description: [系统管理-机构管理，添加管理员保存]
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "adminAddSave")
    @ResponseBody
    public String adminAddSave(OrgBean orgBean, Model model) throws Exception {
        try {
            orgService.adminAdd(orgBean);
            super.message("添加成功！");
            orgService.insertLog(super.MakeLogBean(super.LOG_ADD_KEY, "添加机构管理员", orgBean.toString()));
        } catch (BaseException e) {
            super.message("添加失败: " + e.getMessage());
            return queryList(model);
        }
        return "保存成功";
    }

    /**
     * Author:shanzhitong Create At:2017-09-01 
     * Description: [系统管理-机构管理，获取菜单分组树]
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "getMenuList")
    private String getMenuList(Model model) throws BaseException {
        List<MenuBean> menuList = menuService.getMenuList(paramMap);
        String[] orgIds = request.getParameterValues("ids");
//        super.paramMap.put("ids", orgIds);
        List<BaseBean> baseBeanList = this.orgService.getMenus(orgIds);
        JSONArray dataArry = new JSONArray();
        if (null != menuList && menuList.size() > 0) {
            for (MenuBean menu : menuList) {
                JSONObject obj = new JSONObject();
                obj.put("id", menu.getMenuId());
                obj.put("pId", menu.getParentMenu());
                obj.put("name", menu.getMenuName());
                obj.put("leafLev", "3");// 默认放置三级类型信息
                dataArry.add(obj);
            }
        }
        String selTypeIds = "";
        if (null != baseBeanList && baseBeanList.size() > 0) {
            for (BaseBean base : baseBeanList) {
                if (!"01".equals(base.getCode())) {
                    selTypeIds = selTypeIds + "," + base.getCode();
                }
            }
        }
        selTypeIds = selTypeIds.trim();
        model.addAttribute("selTypeIds", selTypeIds.replaceAll(",(.*)", "$1"));
        model.addAttribute("menuTree", dataArry.toString());
        model.addAttribute("orgIds", orgIds);
        return BASE_PATH + "popup/" + "orgMenuList";
    }

    /**
     * Author:shanzhitong Create At:2017-09-01 
     * Description: [系统管理-机构管理，给组织机构分配菜单权限]
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "authMenuToOrg")
    @ResponseBody
    private String authMenuToOrg(Model model) throws Exception {
        try {
            String ids = request.getParameter("ids");
            String[] menuIds = StringUtil.isEmpty(ids) ? null : ids.split(",");
            String orgId = request.getParameter("orgId");
            super.paramMap.put("ids", menuIds);
            super.paramMap.put("orgId", orgId);
            orgService.distributeOrgMenu(paramMap);
            orgService.insertLog(super.MakeLogBean(super.LOG_UPDATE_KEY, "给组织机构分配菜单", paramMap.toString()));
            super.message("分配菜单成功！");
        } catch (BaseException e) {
            super.message("分配菜单失败: " + e.getMessage());
            return queryList(model);
        }
        return "修改成功";
    }
}
